<?php

namespace App\Http\Controllers\Admin;

use App\Models\Message;
use App\Models\MessageTpl;
use App\Traits\ValidationTrait;
use Illuminate\Container\BoundMethod;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use OSS\OssClient;
use Silber\Bouncer\Bouncer;
use App\Models\Send;

class MessageTplController extends Controller
{
    use ValidationTrait;
    public function __construct()
    {
        view()->share('menu', 'msg');
    }

    /**
     * 系统消息模板列表
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
//        $bouncer  = Bouncer::create();
//        $bouncer->allow('管理员2')->to('asdqwe');
        //消息类型数组
        $msg_name = ['未知','系统消息'];
        $like_title = '';
        if (empty($request->post('like_title'))) {
            $list = MessageTpl::with(['admin' => function ($query) {
                $query->select('username', 'id');
            }])
                ->where(['is_show'=>1])
                ->orderBy('id', 'DESC')
                ->paginate(15);
        } else {
            $like_title = $request->post('like_title');
            $list = MessageTpl::with(['admin' => function ($query) {
                $query->select('username', 'id');
            }])
                ->where(['is_show'=>1])
                ->where('title', 'like', '%' . $like_title . '%')
                ->orderBy('id', 'DESC')
                ->paginate(15);
            $url_data = compact('like_title');
        }
        $page_num = $list->firstItem();

        return view('admin/msg_tpl/tpl_index',compact('list', 'page_num', 'like_title', 'url_data','msg_name'));
    }

    /**
     * 添加模板信息页面
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('admin/msg_tpl/tpl_create');

    }

    /**
     * 添加模板信息到数据库
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validator = $this->verify($request, 'validation.msg_tpl');
        if ($validator->fails()) {
            $messages = $validator->messages()->first();
            return back()->with(['msg' => $messages])->withInput();
        }
        $data = $request->input();

        unset($data['_token']);
        unset($data['image']);
        unset($data['s']);

        $data['admin_id'] = session('admin_info.id');
        (new MessageTpl())->firstOrCreate($data);
        return back()->with(['msg' => '添加成功', 'status' => 1, 'msg_url' => '/admin/tpl_index']);
    }

    /**
     * 编辑消息模板页面
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {

        $list = MessageTpl::find($id);
        $list['icon_url'] = empty($list['icon'])?'':config('alioss.host').'/'.$list['icon'];

        return view('admin/msg_tpl/tpl_edit', compact('list'));
    }

    /**
     * 更新消息模板到数据库
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request,$id)
    {
        $validator = $this->verify($request, 'validation.msg_tpl');
        if ($validator->fails()) {
            $messages = $validator->messages()->first();
            return back()->with(['msg' => $messages])->withInput();
        }
        $data = $request->input();
        unset($data['_token']);
        unset($data['image']);
        unset($data['s']);

        $data['admin_id'] = session('admin_info.id');
        (new MessageTpl())->where('id', $id)->update($data);
        return back()->with(['msg' => '修改成功', 'status' => 1, 'msg_url' => '/admin/tpl_index']);

    }

    /**
     * 删除
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param Request $request
     * @return array
     */
    public function destroy(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return ['status' => 0, 'msg' => '缺少参数'];
        }
        MessageTpl::where(['id'=>$id])->update(['is_show'=>0]);
        return ['status' => 1, 'msg' => '删除成功'];
    }


    /**
     * 系统消息列表
     * @date 2018/03/09
     * @author 杨刚
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function message_index(Request $request)
    {
        $like_title = '';
        if (empty($request->post('like_title'))) {
            $list = Message::with(['admin' => function ($query) {
                $query->select('username', 'id');
            }])
                ->orderBy('id', 'DESC')
                ->paginate(15);
        } else {
            $like_title = $request->post('like_title');
            $list = Message::with(['admin' => function ($query) {
                $query->select('username', 'id');
            }])
                ->where('title', 'like', '%' . $like_title . '%')
                ->orderBy('id', 'DESC')
                ->paginate(15);
            $url_data = compact('like_title');
        }
        $page_num = $list->firstItem();

        return view('admin/user/message_index', compact('list', 'page_num', 'like_title', 'url_data'));
    }

    /**
     * 添加系统消息页面
     * @date 2017/03/09
     * @author yanggang
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function message_create()
    {
        return view('admin/user/message_create');
    }

    /**
     * 添加系统消息进数据库
     * @date 2018/03/09
     * @author yanggang
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function message_store(Request $request)
    {
        //get param
        $title = $request->get('title');
        $msg_type = $request->get('msg_type');
        $content = $request->get('content');
        $type = $request->get('type');
        $userids = $request->get('userids');
        // check
        if (empty($title) || !isset($msg_type) || empty($content) || !isset($type)) {
            return back()->with(['msg' => '信息填写不全', 'status' => 0]);
        }
        if ($type == 0 && !$userids) {
            return back()->with(['msg' => '请选择指定人员', 'status' => 0]);
        }
        $model = new Send();
        // save to database
        $data = compact('title', 'content', 'type');
        $data['admin_id'] = session('admin_info.id');
        $data['tpl_id'] = 0;
        if ($type == 0 && !empty($userids)) {
            $datas = [];
            $ids = explode(',', $userids);
            foreach ($ids as $item) {
                $data['uid'] = $item;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['updated_at'] = date('Y-m-d H:i:s');
                array_push($datas, $data);
                $idss[] = $item.substr(User::where('id',$item)->first()->token, 0, 6);
            }
            Message::insert($datas);
            $model->send(1,array_values($idss),$title,$content,1);
        } else {
            Message::create($data);
            $model->sends($title,$content,1);
        }
        return back()->with(['msg' => '添加成功', 'status' => 1, 'msg_url' => '/admin/message_index']);
    }

    /**
     * 系统消息编辑页面
     * @date 2018/03/09
     * @author yanggang
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function message_edit($id)
    {
        $list = Message::find($id);
        return view('admin/user/message_edit', compact('list'));
    }

    /**
     * 更新系统消息
     * @date 2018/03/09
     * @author yanggang
     * @param Request $request
     * @param $id
     */
    public function message_update(Request $request, $id)
    {
        $title = $request->get('title');
        $msg_type = $request->get('msg_type');
        $content = $request->get('content');
        $type = $request->get('type');
        // check
        if (empty($title) || !isset($msg_type) || empty($content) || !isset($type)) {
            return back()->with(['msg' => '信息填写不全', 'status' => 0]);
        }
        // save to database
        $data = compact('title', 'content', 'type');
        $data['admin_id'] = session('admin_info.id');
        (new Message())->where('id', $id)->update($data);
        return back()->with(['msg' => '修改成功', 'status' => 1, 'msg_url' => '/admin/message_index']);
    }

    /**
     * 添加系统消息时，选择用户
     * @date 2018/03/23
     * @author yanggang
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function select_user(Request $request)
    {
        $account = $request->get('account');
        $phone = $request->get('phone');
        $email = $request->get('email');

        $map = [
            ['status', 1]
        ];
        if (!empty($account)) {
            array_push($map, ['account', 'like', '%' . $account . '%']);
        }
        if (!empty($phone)) {
            array_push($map, ['phone', 'like', '%' . $phone . '%']);
        }
        if (!empty($email)) {
            array_push($map, ['email', 'like', '%' . $email . '%']);
        }
        $url_data = compact('account', 'phone', 'email');
        $list = User::where($map)->paginate(15);
        $page_num = $list->firstItem();
        return view('admin/user/select_user', compact('list', 'page_num', 'account', 'phone', 'email', 'url_data'));
    }

    /**
     * 删除系统消息
     * @param Request $request
     * @return array
     */
    public function message_destroy(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return ['status' => 0, 'msg' => '缺少参数'];
        }
        Message::destroy($id);
        return ['status' => 1, 'msg' => '删除成功'];
    }

    public function upload_img(Request $request)
    {
        //阿里云操作类
        $oss = new OssClient(config('alioss.accessKeyId'), config('alioss.accessKeySecret'), config('alioss.endpoint'));
        //如果有image参数
        if ($request->has('image')) {
            //接收文件
            $image = $request->file('image');
            //文件路径变量
            $filePath = [];
            //遍历文件
            foreach ($image as $key => $value) {
                //文件验证成功
                if ($value->isValid()) {
                    //防止多次上传
                    if (!empty($value)) {
                        //临时文件的绝对路径
                        $realPath = $value->getRealPath();
                        // 扩展名
                        $ext = $value->getClientOriginalExtension();
                        //文件名
                        $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext;
                        //oss路径
                        $osspath  = 'block_chain/' . $filename;
                        //上传文件到阿里云
                        $oss->uploadFile(config('alioss.bucket'), $osspath, $realPath);
                        //判断对象是否存在
                        $does = $oss->doesObjectExist(config('alioss.bucket'), $osspath);
                        //oss文件不存在
                        if (!$does) {
                            //返回错误提示
                            return response()->json(['status' => 0, 'msg' => '文件上传oss失败']);
                        }
                        //写入数组
                        $filePath[$key] = $osspath;
                    }
                } else {
                    //验证失败
                    return respF(1038);
                }
            }
            //成功返回文件路径数组
            return response()->json(['status' => 1, 'msg' => '上传成功', 'data' => $filePath]);
        }
        //没有image，返回错误提示
        return respF(1011);
    }
}
